package com.fly.feishu.domain.service.impl;

import com.fly.feishu.api.dto.DeptCondition;
import com.fly.feishu.api.dto.DeptSyncDto;
import com.fly.feishu.api.service.FeishuContractService;
import com.fly.feishu.domain.enums.DataSyncType;
import com.fly.feishu.domain.service.DeptSyncService;
import com.fly.feishu.infrastructure.persistent.mapper.DepartmentMapper;
import com.fly.feishu.infrastructure.persistent.po.Department;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

@Service
@Slf4j
public class DeptSyncServiceImpl implements DeptSyncService {
    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private FeishuContractService feishuContractService;

    @Override
    public void sync(Long id, DataSyncType type) {
        Example example = new Example(Department.class);
        example.createCriteria().andEqualTo("id", id);
        Department department = departmentMapper.selectOneByExample(example);
        if (department == null) {
            log.warn("部门数据同步，未查询到相关部门信息");
            return;
        }
        switch (type) {
            case POST:
                post(department);
                break;
            case PUT:
                put(department);
                break;
            case DELETE:
                delete(id);
                break;
        }
    }

    private void post(Department department) {
        feishuContractService.createDept(convertEntity2Dto(department));
    }

    private void put(Department department) {
        feishuContractService.updateDept(convertEntity2Dto(department));
    }

    private void delete(Long id) {
        feishuContractService.deleteDept(id.toString());
    }

    private DeptSyncDto convertEntity2Dto(Department department) {
        DeptSyncDto deptSyncDto = new DeptSyncDto();
        deptSyncDto.setDepartmentId(department.getId().toString());
        DeptSyncDto.DepartmentStatus departmentStatus = new DeptSyncDto.DepartmentStatus();
        deptSyncDto.setStatus(departmentStatus);
        Integer sort = department.getSort();
        if (sort != null) {
            deptSyncDto.setOrder(sort.toString());
        }
        deptSyncDto.setName(department.getName());
        deptSyncDto.setCreateGroupChat(false);
        Integer leaderUserId = department.getLeaderUserId();
        if (leaderUserId != null) {
            deptSyncDto.setLeaderUserId(leaderUserId.toString());
        }

        Integer parentDepartmentId = department.getParentDepartmentId();
        if (parentDepartmentId != null) {
            deptSyncDto.setParentDepartmentId(department.getParentDepartmentId().toString());
        }
        return deptSyncDto;
    }
}
